<template>
  <ui-container>
    <template #extra>
      <u-button type="primary" @click="handleOnClickToAdd"> 新增 </u-button>
    </template>
    <template #search>
      <u-form :schema="searchFormSchema" :dataSource="searchData">
        <template #footer>
          <u-button @click="handleOnClickToSearch" type="primary"
            >搜索</u-button
          >
        </template>
      </u-form>
    </template>

    <template #container>
      <a-table 
        :columns="columns"
        :data-source="pageData"
        :rowKey="(record) => record.id"
        :pagination="pagination"
        :loading="loading"
        @change="handleOnChangeToLoadTable"
      >
        <template #ruleGroupId="{ record }">
          <a-tag  color="pink"> {{record.ruleGroupName}} </a-tag>
        </template>
        <template #ruleStatus="{ record }">
          <a-switch
            v-model:checked="record.ruleStatus"
            @change="
              (checked) => handleChangeToUpdateStatus(checked, record.id)
            "
          >
            <template #checkedChildren><check-outlined /></template>
            <template #unCheckedChildren><close-outlined /></template>
          </a-switch>
        </template>
        <template #ruleIsDefault="{ record }">
          <a-switch
            v-model:checked="record.ruleIsDefault"
            @change="
              (checked) => handleChangeToUpdateDefault(checked, record.id)
            "
          >
            <template #checkedChildren><check-outlined /></template>
            <template #unCheckedChildren><close-outlined /></template>
          </a-switch>
        </template>
        <template #action="{ record }">
          <u-button
            type="link"
            title="编辑"
            @click="handleOnClickToEdit(record)"
            >编辑</u-button
          >
          <u-button
            type="link"
            title="删除"
            @click="handleOnClickToDelete(record.id)"
            >删除</u-button
          >
          <u-button
            type="link"
            title="授权"
            @click="handleOnClickToAuthorize(record)"
            >资源授权</u-button
          >
        </template>
      </a-table>
    </template>
  </ui-container>

  <a-drawer
    :title="formModalTitle"
    placement="right"
    width="620"
    :closable="false"
    :visible="formModal"
    @close="handleOnClickToCloseDrawer"
  >
    <u-form :schema="schema" :dataSource="form" ref="form"> </u-form>
    <div
      :style="{
        position: 'absolute',
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e8e8e8',
        padding: '10px 16px',
        textAlign: 'right',
        left: 0,
        background: '#fff',
        borderRadius: '0 0 4px 4px',
      }"
    >
      <u-button
        type="primary"
        style="margin-right: 8px"
        @click="handleOnClickToCloseDrawer"
      >
        关闭
      </u-button>
      <u-button type="primary" color="#28a745" @click="handleOnClickToSubmit">
        提交
      </u-button>
    </div>
  </a-drawer>
</template>

<script>
import UIContainer from "basicLayoutComponent/UIContainer";
import UICLI from "components/ui-cli";
import { Table, Switch, Drawer, Tag } from "ant-design-vue";

import { CheckOutlined, CloseOutlined } from "@ant-design/icons-vue";

import Index from "./index";

import {
  getRolePage,
  getRoleGroupList,
  deleteRoleById,
  updateRoleById,
  saveRole,
  patchRoleById,
} from "@/access/api/role/index";

import { confirm, showMess, clearForm, set2Form } from "utils/Util";

export default {
  name: "RoleList",
  components: {
    UButton: UICLI.UButton,
    UForm: UICLI.UForm,
    UiContainer: UIContainer,
    ATable: Table,
    ATag: Tag,
    CheckOutlined,
    CloseOutlined,
    ADrawer: Drawer,
    ASwitch: Switch,
  },
  data() {
    return {
      searchFormSchema: Index.searchFormSchema,
      columns: Index.columns,
      schema: Index.schema,
      pageData: [],
      pagination: {},

      loading: false,

      searchData: {
        currentIndex: 1,
        ruleGroupoId: "",
        ruleStatus: ""
      },
      formModal: false,
      formModalTitle: "添加角色",
      form: {
        id: "",
        ruleGroupId: "",
        ruleName: "",
        ruleDesc: "",
        ruleStatus: 0,
        ruleIsDefault: 0,
        ruleIsCommon: 0,
      },
    };
  },
  methods: {
    getRolePage() {
      this.loading = true;
      getRolePage(this.searchData).then((res) => {
        if (res) {
          this.loading = false;

          this.pageData = res.datas;

          const pagination = { ...this.pagination };
          pagination.total = res.pagination.totalCount;
          this.pagination = pagination;
        }
      });
    },
    handleOnChangeToLoadTable(pagination, filters, sorter) {
      this.searchData.currentIndex = pagination.current;
      this.getRolePage();
    },
    handleOnClickToSearch() {
      this.getRolePage();
    },
    getRoleGroupList() {
      getRoleGroupList().then((res) => {
        if (res) {
          this.searchFormSchema.groups[0].fields[0].sourceData = res;
          this.schema.groups[0].fields[0].sourceData = res;
        }
      });
    },
    handleOnClickToDelete(id) {
      confirm(() => {
        deleteRoleById({ id }).then((res) => {
          if (res) {
            showMess("角色删除成功");
            this.getRolePage();
          }
        });
      }, "确认是否删除当前角色？");
    },
    handleOnClickToAdd() {
      clearForm(this.form);
      this.formModal = true;
    },
    handleOnClickToEdit(record) {
      this.formModalTitle = "修改角色";
      this.formModal = true;

      set2Form(this.form, record);
    },
    handleOnClickToSubmit() {
      this.$refs.form.$refs.form
        .validate()
        .then(() => {
          if (this.form.id) {
            //修改
            updateRoleById(this.form).then((res) => {
              if (res) {
                this.formModal = false;
                showMess("修改成功");
                this.getRolePage();
              }
            });
          } else {
            // 保存
            saveRole(this.form).then((res) => {
              if (res) {
                this.formModal = false;
                showMess("添加成功");
                this.getRolePage();
              }
            });
          }
        })
        .error((error) => {
          console.info(error);
        });
    },
    handleOnClickToAuthorize(record) {
      this.$router.push(`/ruleAuthorize/rule/${record.id}`);
    },
    handleChangeToUpdateStatus(checked, id) {
      patchRoleById({
        id,
        ruleStatus: checked ? 1 : 0,
      }).then((res) => {
        if (res) {
          if (checked) showMess("角色已启用");
          else showMess("角色已禁用");
        }
      });
    },
    handleChangeToUpdateDefault(checked, id) {
      /**
       * 1. 先通过ID得到当前角色
       * 2. 通过当前角色的角色组ID将ruleIsDefault设置为0
       * 3. 再将当前角色的ruleIsDefault设置为1
       */
      patchRoleById({
        id: id,
        ruleIsDefault: checked ? 1 : 0,
      }).then((res) => {
        if (res) {
          if (checked) showMess("已设置为默认角色");
          else showMess("已取消默认角色");
          this.getRolePage();
        }
      });
    },
    handleOnClickToCloseDrawer() {
      this.formModal = false;
    },
  },
  created() {
    this.getRoleGroupList();
    this.getRolePage();
  },
  watch: {
    formModal(newFormModal) {
      if (newFormModal) {
        this.getRoleGroupList();
      }
    },
  },
};
</script>

<style lang="less" scoped>
</style>